package org.jeecg.modules.demo.yyc.reportdaily.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.yyc.reportdaily.entity.PlatformDaily;
import org.jeecg.modules.demo.yyc.reportdaily.service.impl.PlatformDailyServiceImpl;
import org.jeecg.modules.demo.yyc.setting.businessplatform.entity.BusinessPlatform;
import org.jeecg.modules.demo.yyc.setting.businessplatform.service.IBusinessPlatformService;
import org.jeecg.modules.demo.yyc.setting.dailyItem.entity.DailyItem;
import org.jeecg.modules.demo.yyc.setting.dailyItem.service.IDailyItemService;
import org.jeecg.modules.demo.yyc.setting.store.entity.Store;
import org.jeecg.modules.demo.yyc.setting.store.service.IStoreService;
import org.jeecg.modules.demo.yyc.unit.DateUnit;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 类说明
 *
 * @ClassName DailyImportUtil
 * @Description TODO
 * @Author think
 * @Date 2022/11/20 22:56
 **/
@Service
public class DailyImportUtil {

    @Resource
    IBusinessPlatformService businessPlatformService;

    @Resource
    IStoreService storeService;

    @Resource
    IDailyItemService dailyItemService;

    @Resource
    IPlatformDailyService platformDailyService;

    public BusinessPlatform getPlatform(Map<String, Object> listItem, PlatformDailyServiceImpl platformDailyService){
        Object platformName = listItem.get("平台");
        if(platformName == null){
            throw new RuntimeException("平台不能为空");
        }
        BusinessPlatform platform = new BusinessPlatform();
        platform.setName(platformName.toString());
        QueryWrapper<BusinessPlatform> queryWrapper = QueryGenerator.initQueryWrapper(platform, null);
        platform = businessPlatformService.getOne(queryWrapper);
        if(platform == null){
            throw new RuntimeException("系统不存在名为“"+platformName+"”的平台");
        }
        return platform;
    }

    public Store getStore(Map<String, Object> listItem, BusinessPlatform platform){
        Object storeName = listItem.get("店铺");
        if(storeName == null){
            throw new RuntimeException("店铺不能为空");
        }
        Store store = new Store();
        store.setName(storeName.toString());
        store.setPlatformId(platform.getId());
        QueryWrapper<Store> queryWrapper = QueryGenerator.initQueryWrapper(store, null);
        store = storeService.getOne(queryWrapper);
        if(store == null){
            throw new RuntimeException(platform.getName()+"平台下不存在名为“"+storeName+"”的店铺");
        }
        return store;
    }

    /**
     * 检查上传上来excel的表头，是否和平台的日报要素规则吻合
     *
     * @param listItem             上传excel解析后形成的一行的map
     * @param platform             平台
     * @param platformDailyService
     */
    public void checkExcelDailyItem(Map<String, Object> listItem, BusinessPlatform platform, PlatformDailyServiceImpl platformDailyService){
        Set<String> excelKeys = listItem.keySet();
        List<String> dailyItemKeys = new ArrayList<>();
        List<DailyItem> dailyItemList = dailyItemService.getByPlatformId(platform.getId());
        dailyItemList.forEach(item -> {
            dailyItemKeys.add(item.getName());
        });
        excelKeys.forEach(key -> {

            if("平台".equals(key) || "店铺".equals(key) || "时间".equals(key)){
                return;
            }

            if(!dailyItemKeys.contains(key)){
                throw new RuntimeException(platform.getName()+"平台下不存在名为“"+key+"”的要素");
            }
        });
    }

    /**
     * 根据上传的excel解析成对应的PlatformDaily集合，此处默认已经调用checkExcelDailyItem检查过了
     *
     * @param listItem
     * @param platform
     * @return
     */
    public List<PlatformDaily> getPlatformDaily(List<Map<String, Object>> listItem, BusinessPlatform platform){
        List<DailyItem> dailyItemList = dailyItemService.getByPlatformId(platform.getId());
        List<PlatformDaily> platformDailyList = new ArrayList<>();

        //循环excel里的每一行
        listItem.forEach(mapItem -> {
            Store store = getStore(mapItem,platform);
            //给每一行分配组id
            String dailyGroupid = platformDailyService.getDailyGroupId();
            //循环日报要素集合，组装日报数据
            dailyItemList.forEach(item -> {
                Object valueObj = mapItem.get(item.getName());
                if(valueObj == null) return;
                if(valueObj.toString().trim().equals("")) return;
                Date dataTime = getDataTime(mapItem,platform,store);
                String value = mapItem.get(item.getName()).toString();
                PlatformDaily platformDaily = new PlatformDaily();
                platformDaily.setPlatformId(platform.getId());
                platformDaily.setStoreId(store.getId());
                platformDaily.setDailyItemId(item.getId());
                platformDaily.setValue(value);
                platformDaily.setDatatime(dataTime);
                platformDaily.setDailyId(dailyGroupid);
                platformDailyList.add(platformDaily);
            });
        });

        return platformDailyList;
    }

    private Date getDataTime(Map<String, Object> excelItem,BusinessPlatform platform,Store store){
        Object timeObj = excelItem.get("时间");
        if(timeObj == null) throw new RuntimeException("时间不能为空");
        if(timeObj.toString().trim().equals("")) throw new RuntimeException("时间不能为空");
        Date datatime;
        try {
            datatime = DateUnit.localDatetoDate(DateUnit.parseDate(timeObj.toString(),"yyyy年MM月dd日"));
        }
        catch(Exception e){
            throw new RuntimeException("时间格式必须为：yyyy年MM月dd日，比如2022年11月21日",e);
        }

        PlatformDaily platformDaily = new PlatformDaily();
        platformDaily.setPlatformId(platform.getId());
        platformDaily.setStoreId(store.getId());
        platformDaily.setDatatime(datatime);
        QueryWrapper<PlatformDaily> queryWrapper = QueryGenerator.initQueryWrapper(platformDaily, null);
        if(platformDailyService.count(queryWrapper) > 0){
            throw new RuntimeException(String.format("%s平台下%s店铺已存在%s的日报，不能重复导入",platform.getName(),store.getName(),timeObj.toString()));
        }

        return datatime;
    }
}
